<template>
  <div class="payment">
    <el-card class="payment-card">
      <div slot="header" class="header">
        <span>订单支付</span>
      </div>

      <div class="order-info">
        <div class="amount">
          <span class="label">支付金额</span>
          <span class="price">¥{{ order.totalAmount || '0.00' }}</span>
        </div>
        <div class="order-no">
          <span class="label">订单编号</span>
          <span>{{ order.orderNo || '加载中...' }}</span>
        </div>
      </div>

      <div class="payment-methods">
        <h3>选择支付方式</h3>
        <el-radio-group v-model="paymentMethod">
          <div class="payment-method-item" :class="{ active: paymentMethod === 'alipay' }">
            <el-radio label="alipay">
              <div class="method-content">
                <img src="@/assets/alipay.png" alt="支付宝">
                <span>支付宝支付</span>
              </div>
            </el-radio>
          </div>
          <div class="payment-method-item" :class="{ active: paymentMethod === 'wechat' }">
            <el-radio label="wechat">
              <div class="method-content">
                <img src="@/assets/wechat.png" alt="微信">
                <span>微信支付</span>
              </div>
            </el-radio>
          </div>
        </el-radio-group>
      </div>

      <div class="qrcode-section" v-if="showQRCode">
        <div class="qrcode-wrapper">
          <img :src="qrcodeUrl" alt="支付二维码">
        </div>
        <p class="tip">请使用{{ paymentMethod === 'alipay' ? '支付宝' : '微信' }}扫码支付</p>
        <div class="countdown">
          支付倒计时：{{ formatTime(countdown) }}
        </div>
      </div>

      <div class="actions">
        <el-button type="primary" @click="handlePay" :loading="paying" v-if="!showQRCode">
          立即支付
        </el-button>
        <el-button @click="cancelPay">取消支付</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getOrderDetail, payOrder, cancelOrder } from '@/api/order'

export default {
  name: 'Payment',
  data() {
    return {
      order: {
        id: '',
        orderNo: '',
        totalAmount: 0,
        status: 0
      },
      paymentMethod: 'alipay',
      paying: false,
      showQRCode: false,
      qrcodeUrl: '',
      countdown: 900, // 15分钟支付倒计时
      timer: null
    }
  },
  created() {
    this.fetchOrderDetail()
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  methods: {
    async fetchOrderDetail() {
      try {
        const orderId = this.$route.params.orderId
        const response = await getOrderDetail(orderId)
        if (response.code === 200) {
          this.order = response.data
        } else {
          this.$message.error('获取订单信息失败')
          this.$router.push('/main/shop/orders')
        }
      } catch (error) {
        this.$message.error('获取订单信息失败')
        this.$router.push('/main/shop/orders')
      }
    },

    async handlePay() {
      if (!this.paymentMethod) {
        this.$message.warning('请选择支付方式')
        return
      }

      try {
        this.paying = true
        const response = await payOrder(this.order.id, this.paymentMethod)
        
        if (response.code === 200) {
          this.$message.success('支付成功')
          // 跳转到订单列表页面
          this.$router.push('/main/shop/orders')
        } else {
          this.$message.error(response.message || '支付失败')
        }
      } catch (error) {
        console.error('支付失败:', error)
        this.$message.error('支付失败，请稍后重试')
      } finally {
        this.paying = false
      }
    },

    startCountdown() {
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--
        } else {
          clearInterval(this.timer)
          this.$message.warning('支付超时，请重新下单')
          this.$router.push('/main/shop/orders')
        }
      }, 1000)
    },

    formatTime(seconds) {
      const minutes = Math.floor(seconds / 60)
      const remainingSeconds = seconds % 60
      return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
    },

    cancelPay() {
      this.$confirm('确定要取消支付吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await cancelOrder(this.order.id)
          if (response.code === 200) {
            this.$message.success('订单已取消')
            this.$router.push('/main/shop/orders')
          } else {
            this.$message.error(response.message || '取消订单失败')
          }
        } catch (error) {
          console.error('取消订单失败:', error)
          this.$message.error('取消订单失败，请稍后重试')
        }
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.payment {
  padding: 20px;

  .payment-card {
    max-width: 800px;
    margin: 0 auto;

    .header {
      font-size: 18px;
      font-weight: bold;
    }

    .order-info {
      text-align: center;
      padding: 30px 0;

      .amount {
        margin-bottom: 15px;

        .label {
          font-size: 16px;
          margin-right: 10px;
        }

        .price {
          font-size: 24px;
          color: #f56c6c;
          font-weight: bold;
        }
      }

      .order-no {
        color: #666;

        .label {
          margin-right: 10px;
        }
      }
    }

    .payment-methods {
      margin: 30px 0;

      h3 {
        margin-bottom: 20px;
        font-size: 16px;
      }

      .payment-method-item {
        padding: 15px;
        border: 1px solid #eee;
        border-radius: 4px;
        margin-bottom: 10px;
        cursor: pointer;

        &:hover {
          border-color: #409EFF;
        }

        &.active {
          border-color: #409EFF;
          background-color: #f5f7fa;
        }

        .method-content {
          display: flex;
          align-items: center;
          margin-left: 5px;

          img {
            width: 24px;
            height: 24px;
            margin-right: 10px;
          }
        }
      }
    }

    .qrcode-section {
      text-align: center;
      padding: 30px 0;

      .qrcode-wrapper {
        width: 200px;
        height: 200px;
        margin: 0 auto 20px;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .tip {
        color: #666;
        margin-bottom: 10px;
      }

      .countdown {
        color: #f56c6c;
        font-size: 16px;
      }
    }

    .actions {
      text-align: center;
      margin-top: 30px;
    }
  }
}
</style> 